import datetime as dt
import operator
import os
import sys
sys.path.append(r'code/frame') 
from training.ml_frame.month_rolling.data_split_month_ml import Rolling_eval_split_month


from BluePrint import QuantBuider
from data_read.get_feature import Get_feature_data
from data_read.get_label import Get_label_data
from training.ml_frame.month_rolling.IC_record import Ic_record
from training.ml_frame.month_rolling.ml_train import Ml_rolling_trin

# 保证处理矩阵为n*50

class Quant(QuantBuider):
    def __init__(self, args) -> None:
        for k, v in args.time_param.items():
            args.time_param[k] = dt.datetime.strptime(v, '%Y-%m')
        self.args = args 

    def get_data(self, Get_feature=Get_feature_data, Get_label=Get_label_data):
        gf = Get_feature(self.args)
        feature, codes_f, times_f, self.args.feature_list = gf.get_feature()
        gl = Get_label(self.args)
        label, codes_l, times_l = gl.get_label_reg()
        print('检查feature与labe时间索引是否对齐：', operator.eq(times_f.tolist(), times_l.tolist()))
        print('检查feature与labe品种索引是否对齐：', operator.eq(codes_f.tolist(), codes_l.tolist()))
        print(f'使用特征数量：{len(self.args.feature_list)} 具体为： {self.args.feature_list}')
        if  self.args.varieties is not None:
            print(f'使用品种数量：{len(self.args.varieties)} 具体为： {self.args.varieties}')
        return feature, label, codes_f, times_f     
                       
    def rolling_train(self, codes, times, feature, label):
        data_sp = Rolling_eval_split_month(feature, label,  times, self.args)
        ic_re = Ic_record(codes, self.args.predict_save)
        ml_train = Ml_rolling_trin(self.args)
        for _ in range(0, data_sp.out_month_num, self.args.rolling_step):
            if self.args.rolling_method == 'cum':
                feature_train, feature_eval, feature_out, label_train, label_eval, label_out, times_train, times_eval, times_out = data_sp.cum_split()
            else:
                feature_train, feature_eval, feature_out, label_train, label_eval, label_out, times_train, times_eval, times_out = data_sp.rolling_split()
            train_pred, Y_insampl, eval_pred, eval_Y, out_pred,  out_Y = ml_train.forard_process(feature_train, feature_eval, feature_out, label_train, label_eval, label_out, data_sp.out_month_root, self.args.feature_list)
            ic_re.ic_record(out_pred, out_Y, data_sp.out_month_root, times_out, 'test')
            ic_re.ic_record(train_pred, Y_insampl, data_sp.out_month_root, times_train, 'train')
            ic_re.ic_record(eval_pred, eval_Y, data_sp.out_month_root, times_eval, 'eval')
            ic_re.save_ic(self.args.result_root, data_sp.out_month_list)


            

            
            
        
        